var KCS = (function($) {

    /* *
     * ***********************************************************************************************
     * **************************************** 文件上传 ************************************************
     * ***********************************************************************************************
     */
    var Uploader = function(el, settings) {
        // el =  <input ... />
        this.el = el;
        // 上传设置
        this.settings = $.extend({}, this.pluploaderDefaultSettings, this.defaultSettings, settings);
        // 类型扩展实例
        this.ext = null;

        this.init();
    };

    Uploader.prototype = {

        // 插件设置, 用户配置项
        'defaultSettings': {
            // 上传文件类型 : image/单图片, multiImage/多图片, file/文件
            'type': 'multiImage',
            // 上传地址
            'url': 'upload.php',
            // 上传时携带参数
            'param': {},
            // 文件选择器过滤
            'filters': {
                'max_file_size': '2mb',
                'mime_types': [{
                    'title': "请选择图片",
                    'extensions': "jpg,gif,png,jpeg,ico"
                }]
            },
            // 图片压缩
            'resize': {
                'width': 1080,
                'height': 1920,
                'quality': 90,
                'crop': false
            },
            // 默认图片
            'defaultImage': '/Kcdns/Public/Admin/plugins/kcs/images/uploader_default.png',
            // 显示宽度
            'width': 200,
            // 显示高度
            'height': 100,
            // 多文件上传最大数量
            'maxCount': 10,
            //上传响应数据值字段
            'valueField':'id',
            //上传响应数据图片地址字段
            'srcField':'path'
        },

        // plupload 配置
        'pluploaderDefaultSettings': {
            // 运行方式
            runtimes: 'html5,flash,silverlight,html4',
            // 选择文件按钮
            browse_button: null,
            // 容器元素
            container: null,
            // 分段尺寸
            // chunk_size: '10kb',
            // 重命名文件
            unique_names: true,
            filters: {},
            // 图片压缩
            resize: {},
            // flash 插件路径
            flash_swf_url: '/Kcdns/Public/Admin/plugins/kcs/kcs/Moxie.swf',
            // silverlight 插件路径
            silverlight_xap_url: '/Kcdns/Public/Admin/plugins/kcs/kcs/Moxie.xap',
            multiple_queues: true,
            // multipart: false,
            max_file_count: 3,
            // 多文件选择
            multi_selection: false,
            // 文件上传域名称
            file_data_name: 'kcs_uploader_file'
        },

        'init': function() {

            this.el.hide();

            switch (this.settings.type) {
                case 'image':
                    this.ext = new UploaderImage(this);
                    break;
                case 'multiImage':
                    this.ext = new UploaderMultiImage(this);
                    break;
                case 'file':
                    this.ext = new UploaderMultiFile(this);
            }

            this.up = new plupload.Uploader(this.settings);
            this.up.init();

            // 使用 html5 上传的时候使用分段上传
            if (this.up.runtime == 'html5') {
                this.up.setOption('chunk_size', '100000');
            } else {
                this.up.setOption('chunk_size', '0');
            }

            this.bindUploadEvents();
        },

        'bindUploadEvents': function() {

            var context = this;

            // 选择文件后回调
            this.up.bind('FilesAdded', function(uploader, files) {
                context.ext.FilesAdded && context.ext.FilesAdded(uploader, files);
            });

            // 上传进度更新回调
            this.up.bind('UploadProgress', function(uploader, file) {
                context.ext.UploadProgress && context.ext.UploadProgress(uploader, file);
            });

            // 分段上传完成回调
            this.up.bind('ChunkUploaded', function(uploader, file, response) {
                var responseJson = JSON.parse(response.response);
                context.ext.ChunkUploaded && context.ext.ChunkUploaded(uploader, file, responseJson);

            });

            // 文件上传完成回调
            this.up.bind('FileUploaded', function(uploader, file, response) {
                var responseJson = JSON.parse(response.response);
                context.ext.FileUploaded && context.ext.FileUploaded(uploader, file, responseJson);
            });

            // 错误回调
            this.up.bind('Error', function(uploader, error) {
                if (console && console.log) {
                    console.log(error);
                }
                if (error.code == -600) {
                    KCS_INTERFACE.showTip('文件过大', false);
                    return false;
                }
                context.ext.Error && context.ext.Error(uploader, error);
            });

        }
    };

    // 单图片上传
    var UploaderImage = function(main) {

        this.main = main;
        this.settings = this.main.settings;

        // 容器元素
        this.box = null;
        // 图片元素
        this.img = null;
        // 删除按钮
        this.del = null;

        this.init();
    };

    UploaderImage.prototype = {

        'init': function() {
            this.createNode();
        },

        'createNode': function() {

            var context = this;

            var imageSrc = this.main.el.attr('data-src') || this.settings.defaultImage;
            var containerId = 'KCS-UPLOADER-IMAGE-BOX-' + Math.ceil(Math.random() * 1000);
            var pickboxId = 'KCS-UPLOADER-IMAGE-BUTTON-' + Math.ceil(Math.random() * 1000);
            var inlineStyle = {
                'width': this.settings.width,
                'height': this.settings.height,
                'line-height': this.settings.height + 'px'
            };

            var container = $('<div>').addClass('kcs-uploader-image-box').attr('id', containerId).css(inlineStyle);
            var pickbox = $('<div>').addClass('kcs-uploader-image-pickbox').attr('id', pickboxId).css(inlineStyle);
            var img = $('<img>').addClass('kcs-uploader-image-img').attr('src', imageSrc);
            var del = $('<div>').addClass('kcs-uploader-image-del');
            var progress = $('<div>').addClass('kcs-uploader-image-progress').css(inlineStyle).hide();



            container.append(pickbox.append(img), progress, del);
            img.before($('<span>').addClass('kcs-uploader-image-span'));
            this.main.el.after(container);

            // 设置上传插件
            this.settings.container = containerId;
            this.settings.browse_button = pickboxId;

            this.box = container;
            this.img = img;
            this.del = del;
            this.progress = progress;

            // 绑定删除事件
            del.click(function() {
                context.img.attr('src', context.settings.defaultImage);
                context.main.el.val('');
                context.resetDel();
            });

            this.resetDel();
        },

        'resetDel': function() {
            if (this.main.el.val() == '') {
                this.del.hide();
            } else {
                this.del.show();
            }
        },

        'FilesAdded': function(uploader, files) {
            uploader.start();
            this.setLock(uploader, true);
        },

        'UploadProgress': function(uploader, file) {
            this.progress.text(file.percent + '%');
        },

        'ChunkUploaded': function(uploader, file, response) {
            if (response.error) {
                KCS_INTERFACE.showTip(response.error.message, false);
                uploader.stop();
                this.setLock(uploader, false);
            }
        },

        'FileUploaded': function(uploader, file, response) {
            if (response.error) {
                KCS_INTERFACE.showTip(response.error.message, false);
            } else {
                this.main.el.val(response.result.id);
                this.img.attr('src', response.result.url);
                this.resetDel();
            }
            this.setLock(uploader, false);
        },

        'setLock': function(uploader, lock) {
            if (lock) {
                this.del.hide();
                this.progress.show().text('0%');
                uploader.disableBrowse(true);
            } else {
                this.progress.fadeOut('fast');
                uploader.disableBrowse(false);
            }
        }
    };

    // 多图片上传
    var UploaderMultiImage = function(main) {

        this.main = main;
        this.settings = this.main.settings;

        // 多图片上传时可以多选文件
        this.settings.multi_selection = true;

        this.itemClass = 'kcs-uploader-multiimage-item-' + Math.ceil(Math.random() * 1000);

        // 容器元素
        this.box = null;
        // 图片元素
        this.img = null;
        // 添加按钮
        this.add = null;

        this.init();
    };

    UploaderMultiImage.prototype = {

        'init': function() {
            this.createNode();

            var imageList = this.main.el.attr('data-src').split(',');

            for (var i = 0; i < imageList.length; i++) {
                if (imageList[i] != '') {
                    this.createImageNode(imageList[i]);
                }
            }

            this.resetAdd();
        },

        'createNode': function() {

            var context = this;
            var containerId = 'kcs-uploader-multiimage-container-' + Math.ceil(Math.random() * 1000);
            var inlineStyle = {
                'width': this.main.settings.width,
                'height': this.main.settings.height,
                'line-height': this.main.settings.height / 1.1 + 'px',
                'font-size': this.main.settings.height / 1.2
            };
            var container = $('<div>').addClass('kcs-uploader-multiimage-box').attr('id', containerId).css(inlineStyle);
            var add = $('<div>').addClass('kcs-uploader-multiimage-add').text('+').css(inlineStyle);

            container.append(add);

            this.main.el.after(container);
            this.box = container;
            this.add = add;

            // 设置上传插件
            this.settings.container = containerId;
            this.settings.browse_button = add[0];

        },

        // 创建图片展示元素
        'createImageNode': function(src, file) {

            var context = this;
            var inlineStyle = {
                'width': this.main.settings.width,
                'height': this.main.settings.height,
                'line-height': this.settings.height + 'px'
            };

            var imageSrc = src || this.main.settings.defaultImage;
            var container = $('<div>').addClass('kcs-uploader-image-box kcs-uploader-multiimage-box ' + this.itemClass).css(inlineStyle);
            var pickbox = $('<div>').addClass('kcs-uploader-image-pickbox').css(inlineStyle);
            var img = $('<img>').addClass('kcs-uploader-image-img').attr('src', imageSrc);
            var del = $('<div>').addClass('kcs-uploader-image-del').show();
            var progress = $('<div>').addClass('kcs-uploader-image-progress').css(inlineStyle).hide();

            if (src) {
                container.attr('data-src', src);
                progress.hide();
            }

            if (file) {
                container.attr('id', file.id);
                progress.text('0%').show();
            }

            container.append(pickbox.append(img), progress, del);
            this.box.before(container);

            img.before($('<span>').addClass('kcs-uploader-image-span'));

            // 绑定删除事件
            del.click(function() {
                container.remove();
                if (file) {
                    context.main.up.removeFile(file.id);
                };
                context.resetAdd();
                context.asyncVal();
            });
        },

        'getImageList': function() {
            var imageList = [];
            $('.' + this.itemClass).each(function() {
                var src = $(this).attr('data-src');
                var value = $(this).attr('data-value');
                if (src) {
                    imageList.push({value:value,src:src});
                }
            });
            return imageList;
        },

        'asyncVal': function() {
            var imageList = this.getImageList();
            var values=[];
            for(var i =0;i<imageList.length;i++){
                values.push(imageList[i]['value']);
            }
            this.main.el.val(values.join(','));
        },

        'resetAdd': function() {
            if ($('.' + this.itemClass).length >= this.settings.maxCount) {
                this.add.hide();
            } else {
                this.add.show();
            }
        },

        'FilesAdded': function(uploader, files) {

            var imageList = this.getImageList();
            var leftCount = this.settings.maxCount - imageList.length;
            var _files = [];
            for (var i = 0; i < files.length; i++) {
                leftCount--;
                if (leftCount < 0) {
                    uploader.removeFile(files[i]);
                } else {
                    _files.push(files[i]);
                }
            }

            if (_files.length) {
                uploader.start();
                for (var i = 0; i < _files.length; i++) {
                    this.createImageNode(false, _files[i]);
                }
            }

            this.resetAdd();
        },

        'UploadProgress': function(uploader, file) {
            $('#' + file.id).find('.kcs-uploader-image-progress').show().text(file.percent + '%');
        },

        'ChunkUploaded': function(uploader, file, response) {
            if (response.error) {
                KCS_INTERFACE.showTip(response.error.message, false);
                uploader.stop();
            }
        },

        'FileUploaded': function(uploader, file, response) {
            if (response.error) {
                KCS_INTERFACE.showTip(response.error.message, false);
            } else {
                $('#' + file.id).attr('data-src', response.result[this.settings.srcField]);
                $('#' + file.id).attr('data-value', response.result[this.settings.valueField]);
                $('#' + file.id).find('.kcs-uploader-image-img').attr('src', response.result.path);
                $('#' + file.id).find('.kcs-uploader-image-progress').hide();
                this.asyncVal();
            }
        },

        'Error': function(uploader, Error) {
            KCS_INTERFACE.showTip('网络错误', false);
            $('#' + Error.file.id).remove();
        }
    };

    // 多文件上传
    var UploaderMultiFile = function(main) {

        this.main = main;
        this.settings = this.main.settings;

        // 多文件上传时可以多选
        this.settings.multi_selection = true;

        this.itemClass = 'kcs-uploader-multifile-item-' + Math.ceil(Math.random() * 1000);

        // 容器元素
        this.box = null;
        // 添加按钮
        this.add = null;

        this.init();
    };

    UploaderMultiFile.prototype = {

        'init': function() {
            this.createNode();

            var fileList = JSON.parse(this.main.el.val()) || [];

            for (var i = 0; i < fileList.length; i++) {
                this.createFileNode(fileList[i]);
            }

            this.resetAdd();
        },

        'createNode': function() {

            var context = this;
            var containerId = 'kcs-uploader-multifile-container-' + Math.ceil(Math.random() * 1000);
            var container = $('<div>').addClass('kcs-uploader-multifile-box').attr('id', containerId);
            var add = $('<div>').addClass('kcs-uploader-multifile-add').text('+');

            container.append(add);

            this.main.el.after(container);
            this.box = container;
            this.add = add;

            // 设置上传插件
            this.settings.container = containerId;
            this.settings.browse_button = add[0];

        },

        // 创建文件展示元素
        'createFileNode': function(data, file) {

            data = data || {};

            var context = this;

            var container = $('<div>').addClass('kcs-uploader-multifile-box ' + this.itemClass).data(data);
            var span = $('<span>').addClass('kcs-uploader-multifile-span').text(data.title);
            var del = $('<div>').addClass('kcs-uploader-multifile-del').html('&times;');
            var progress = $('<div>').addClass('kcs-uploader-image-progress kcs-uploader-multifile-progress').hide();

            if (file) {
                container.attr('id', file.id);
                progress.show();
                span.text('0%');
            }

            container.append(span, progress, del);
            this.box.before(container);

            // 绑定删除事件
            del.click(function() {
                container.remove();
                if (file) {
                    context.main.up.removeFile(file.id);
                };
                context.resetAdd();
                context.asyncVal();
            });
        },

        'getImageList': function() {
            var imageList = [];
            $('.' + this.itemClass).each(function() {
                var data = $(this).data();
                if (data) {
                    imageList.push(data);
                }
            });
            return imageList;
        },

        'asyncVal': function() {
            var imageList = this.getImageList();
            this.main.el.val(JSON.stringify(imageList));
        },

        'resetAdd': function() {
            if ($('.' + this.itemClass).length >= this.settings.maxCount) {
                this.box.hide();
            } else {
                this.box.show();
            }
        },

        'FilesAdded': function(uploader, files) {

            var imageList = this.getImageList();
            var leftCount = this.settings.maxCount - imageList.length;
            var _files = [];
            for (var i = 0; i < files.length; i++) {
                leftCount--;
                if (leftCount < 0) {
                    uploader.removeFile(files[i]);
                } else {
                    _files.push(files[i]);
                }
            }

            if (_files.length) {
                uploader.start();
                for (var i = 0; i < _files.length; i++) {
                    this.createFileNode(false, _files[i]);
                }
            }

            this.resetAdd();
        },

        'UploadProgress': function(uploader, file) {
            $('#' + file.id).find('.kcs-uploader-multifile-span').text(file.percent + '%');
        },

        'ChunkUploaded': function(uploader, file, response) {
            if (response.error) {
                KCS_INTERFACE.showTip(response.error.message, false);
                uploader.stop();
            }
        },

        'FileUploaded': function(uploader, file, response) {
            if (response.error) {
                KCS_INTERFACE.showTip(response.error.message, false);
            } else {
                $('#' + file.id).data({
                    'title': file.name,
                    'src': response.result
                });
                $('#' + file.id).find('.kcs-uploader-multifile-span').text(file.name);
                $('#' + file.id).find('.kcs-uploader-multifile-progress').hide();
                this.asyncVal();
            }
        },

        'Error': function(uploader, Error) {
            KCS_INTERFACE.showTip('网络错误', false);
            $('#' + Error.file.id).remove();
        }
    };


    var KCS_INTERFACE_SCOPE = {
        'uploader': []
    };

    var KCS_INTERFACE = {
        // 分段上传插件
        'uploader': function(el, settings) {

            var instance;

            // flash 或者 siverlight 移动后需要刷新 dom
            if (el == 'reset') {
                for (var i = 0; i < KCS_INTERFACE_SCOPE.uploader.length; i++) {
                    KCS_INTERFACE_SCOPE.uploader[i].up.refresh();
                }
                return true;
            }

            instance = new Uploader(el, settings);
            KCS_INTERFACE_SCOPE.uploader.push(instance);

            return instance;
        }
    };

    return KCS_INTERFACE;

})(jQuery);
